<script lang="ts" setup>
import { get, post, message, loadFile } from '@/utils'
import useTable from '@/hooks/useTable'
import useOptions from '@/hooks/useOptions'
const props = defineProps<{
  show: boolean
  id: number | string
}>()
const emit = defineEmits(['update:show', 'reset', 'confirm'])
const formRef = ref()
const { formatColumns } = useTable()
const searchQuery = reactive({
  categoryId: '',
})
const selectedKeys = ref([])
watch(
  () => selectedKeys.value,
  n => {
    console.log(n)
  }
)
const actionRef = ref()
const pagination = {
  showPageSize: true,
  pageSize: 10,
}
const detail = reactive({
  banner: '',
  name: '',
})
watch(
  () => actionRef.value,
  n => {
    console.log(n)
  }
)
const submit = done => {
  console.log(actionRef.value.getSelected().selectedRows)
  // done(false)
  // return
  formRef.value.validate(err => {
    if (!err) {
      const query = Object.assign({}, detail)
      post(
        {
          url: '/server-shop/sys-seller/goods/save/batch',
          data: actionRef.value.getSelected().selectedRows.map(({ id, ...item }) => Object.assign(item, { importId: id })),
        },
        ({ code, msg }) => {
          message({
            type: code == 200 ? 'success' : 'error',
            content: msg,
          })
          emit('update:show', false)
          emit('confirm')
          done(true)
        },
        () => done(false)
      )
    } else done(false)
  })
}
const request = (params: any, sort: any, filters: any): Promise<any> => {
  return new Promise((resolve, reject) => {
    get(
      {
        url: '/server-shop/sys-seller/goods/com/page',
        data: { pageNum: params.current, ...params, categoryId: searchQuery.categoryId[searchQuery.categoryId.length - 1] },
      },
      ({ data }) => {
        const list: any[] = []
        data.records.map(v => {
          list.push({
            ...v,
            disabled: v.sellerId == -1,
          })
        })
        resolve({
          data: list,
          total: data.total,
          success: true,
        })
      }
    )
  })
}
/**平台商品分类 */
const { options: platformCategory } = useOptions({
  api: '/server-shop/sys-seller/goods/category/tree',
})
/**获取分类的名字做展示 */
const getClassifyName = ids => {
  try {
    const classifyIds = ids && JSON.parse(ids)
    let nameList: string | string[] = []
    classifyIds.map(ids => {
      if (typeof ids == 'string') {
        const [item] = platformCategory.value.filter(f => f.id == ids)
        nameList.push(item.title)
      } else if (ids instanceof Array) {
        function findNodesByIds(tree, idSet, found: any[] = []) {
          for (const node of tree) {
            if (idSet.has(node.id)) {
              found.push(node)
            }
            if (node.children && node.children.length) {
              findNodesByIds(node.children, idSet, found)
            }
          }
          return found
        }
        const _list = findNodesByIds(platformCategory.value, new Set(ids))
        const res: string[] = []
        _list.map(item => {
          res.push(item.title)
        })
        nameList.push(res.join('/'))
      }
    })
    return nameList
  } catch (error) {
    console.log(error)
  }
}
const columns = formatColumns([
  {
    title: '商品ID',
    dataIndex: 'id',
    width: 200,
    valueType: 'digit',
    ellipsis: true,
  },
  { title: '货架号', dataIndex: 'sn', width: 120, hideInSearch: false },
  {
    title: '平台商品分类',
    dataIndex: 'categoryId',
    width: 200,
    // valueEnum: classifyValueEnum,
    formSlotName: 'categoryIdSearch',
    hideInSearch: false,
    ellipsis: true,
  },
  {
    title: '商品图片',
    dataIndex: 'img',
    valueType: 'image',
    width: 90,
  },
  {
    title: '商品名称',
    dataIndex: 'name',
    width: 200,
    hideInSearch: false,
    ellipsis: true,
  },

  {
    title: '商品价',
    dataIndex: 'goodsPrice',
    width: 100,
    valueType: 'money',
  },

  { title: '创建时间', dataIndex: 'createTime', width: 200 },
])
</script>
<template>
  <CModal v-model:visible="props.show" @before-ok="submit" :mask-closable="false" width="70%" title="导入商品" @cancel="emit('update:show', false)">
    <ProTable
      :columns="columns"
      :request="request"
      row-key="id"
      :form-ref="ref => (formRef = ref)"
      :pagination="pagination"
      header-title=""
      @reset="searchQuery.categoryId = ''"
      :params="searchQuery"
      column-resizable
      :default-form-data="{}"
      :bordered="{ cell: true }"
      :action-ref="ref => (actionRef = ref)"
      v-model:selectedRowKeys="selectedKeys"
      :row-selection="{
        type: 'checkbox',
        showCheckedAll: true,
        onlyCurrent: false,
      }"
    >
      <template #option-render="{ dom, reset }">
        <component :is="dom[1]" />
        <component :is="dom[0]" />
      </template>
      <template #categoryIdSearch="{ record }">
        <a-cascader v-model="searchQuery.categoryId" :options="platformCategory" path-mode placeholder="请选择分类" :field-names="{ label: 'title', value: 'id' }" />
      </template>
      <template #categoryId="{ record }">
        <a-space>
          <a-tag v-for="item in getClassifyName(record.categoryId)" color="blue">
            {{ item }}
          </a-tag>
        </a-space>
      </template>
    </ProTable>
  </CModal>
</template>
<style lang="less" scoped></style>
